﻿// -----------------------------------------------------------------------
// <copyright file="FileTransfer.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace ftp
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class FileTransfer : sinetd.Services.ServiceWrapper
    {
        public FileTransfer(sinetd.Config cfg)
            : base("FileTransfer", cfg.GetString("protocol"))
        {
            if (Protocol != null)
                Protocol.Config = "host=" + cfg.GetString("host") + ";port=" + cfg.GetString("port");
        }

        public bool Connect()
        {
            return Protocol.Connect();
        }

        public void Disconnect()
        {
            Protocol.Close();
        }

        public string[] ls()
        {
            Protocol.Send((string)InvokeCall("ls", new object[] { }));
            string ans = Protocol.Recv();
            if (ans != "")
            {
                return ans.Split(';');
            }
            return new string[0];
        }

        public void put(string fileName)
        {
            foreach (string l in (IEnumerable<string>)InvokeCall("put", new object[] { fileName }))
            {
                Protocol.Send(l);
            }
        }

        public void get(string fileName)
        {
            Protocol.Send((string)InvokeCall("get", new object[] { fileName }));
            using (FileStream fs = File.OpenWrite(fileName))
            {
                string[] msg = Protocol.Recv().Split(' ');
                msg = Protocol.Recv().Split(' ');
                while (msg[1] != "end")
                {
                    fs.Write(Convert.FromBase64String(msg[1]), 0, 100);
                    msg = Protocol.Recv().Split(' ');
                }
            }
        }
    }
}
